const path = require("path");

const express = require("express");
const cors = require("cors");
const expressWs = require("express-ws");
const { v4: uuid } = require("uuid");

const { onMessage, onClose } = require("./lib/socketHandler");
const { port } = require("./config");

const app = express();
// 添加websocket服务
const wsInstance = expressWs(app);
// 允许任意跨域请求
app.use(cors());
// 将cache文件夹设置为静态源目录，用于存放hls文件
app.use(express.static("cache"));

app.ws("/stream", (socket, request) => {
  request.clientId = uuid();
  console.log("客户端接入分配id", request.clientId);
  socket.send("成功连接服务端: " + request.clientId);

  socket.on("message", (message) => onMessage(message, socket, request));
  socket.on("close", (error) => onClose(error, socket, request));
});

app.listen(port, () => {
  console.log("服务器已启动，端口：" + port);
  console.warn("Set RTSP stream on http://localhost:" + port + "/index.html");
  console.warn("HLS player on http://localhost:" + port + "/hls-js.html");
  console.warn("Video player on http://localhost:" + port + "/video-js.html");
});

var pathstr = path.join(__dirname, "list.m3u8");
// var pathstr = "E:/test/hls/list.m3u8";
console.log("🚀 ~ file: server.js:37 ~ path:", pathstr);
var pathCell = pathstr.split("/");
if (pathCell.length <= 1) {
  pathCell = pathstr.split("\\");
}

console.log("🚀 ~ file: server.js:38 ~ pathCell:", pathCell);
console.log("🚀 ~ directory:", pathCell[pathCell.length - 2]);

// TODOS ffmpegManager需要改成：启动ffmpeg转换rtsp流成功之后再返回hls地址，失败会返回失败消息
